import $router from '@/router'
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { reSignInRqs, systemNameRqs } from '@/request/api'
import { useCommonStore } from '@/store/main'
import { Utils } from '@/common/utils.js'
import { USER_TYPE_FN } from '@/common/hooks'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' 

const REQUEST_SUCCESS_NO = 0
const DEFAULT_VALID_TIME = 1800
const RE_SIGN_IN_TIME = 1500
const LOGIN = 'login'
const PATH_LOGIN = `/${LOGIN}`
const SET_PASSWORD = 'setPassword'
const PATH_SET_PASSWORD = `/${SET_PASSWORD}`
const pageTitle = ref('')
const routes: RouteRecordRaw[] = [
	{
		path: '/',
		component: () => import(/* webpackChunkName: 'mainView' */ '@/views/MainView.vue'),
		children: [{
			path: '',
			name: 'homeView', 
			meta: {
				title: `${pageTitle.value}首页`
			},
			component: () => import(/* webpackChunkName: 'homeView' */ '@/views/HomeView.vue')
		}, {
			path: 'serviceManage',
			name: 'serviceManage', 
			meta: {
				title: `${pageTitle.value}服务管理`
			},
			component: () => import(/* webpackChunkName: 'serviceManage' */ '@/views/serviceManage/Index.vue')
		}, {
				path: 'configurationExtend',
				name: 'configurationExtend', 
				meta: {
					title: `${pageTitle.value}扩展配置`
				},
				component: () => import(/* webpackChunkName: 'configurationManage' */ '@/views/configurationManage/extendConfiguration/Index.vue')
			},
		]
	}, {
        path: '/:pathMatch(.*)',
        name: 'NotFound',
        meta: {
            title: '404'
        },
        component: () => import(/* webpackChunkName: 'notFound' */ '@/views/NotFound.vue')
    }, {
        path: PATH_LOGIN,
		name: LOGIN,
        meta: {
            title: `${pageTitle.value}登录`,
        },
        component: () => import(/* webpackChunkName: 'login' */ '@/views/Login.vue'),
		beforeEnter: (to, from) => {
			getSystemInfoFn()
		}
    }, {
		path: PATH_SET_PASSWORD,
		name: SET_PASSWORD, 
		meta: {
			title: `${pageTitle.value}修改密码`
		},
		component: () => import(/* webpackChunkName: 'setPassword' */ '@/views/SetPassword.vue')
	}
]
const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	scrollBehavior() {
		// 始终滚动到顶部
		return { top: 0 }
	},
	routes
})

// 页面加载进度条
NProgress.configure({
	showSpinner: false
})

// 获取系统信息
const getSystemInfoFn = async () => {
	const $store = useCommonStore()
	const res = await systemNameRqs()

	if(res?.code === REQUEST_SUCCESS_NO) {
		const data = res.data[0]
		const systemId = data.system_id
		const systemNameCN = data.system_name
		const systemFullname = `${data.system_name} (${data.env})`
		$store.setSystemInfo({
			systemId,
			systemNameCN,
			systemFullname
		})
	}
}

// 刷新 token
const reSignInFn = async () => {
	const $store = useCommonStore()
	const params = {
		user_name: $store.userInfo.userName!
	}
	const res = await reSignInRqs(params)

	if(res?.code === REQUEST_SUCCESS_NO) {
		const data = res.data[0]
		const LOGIN_CURRENT_TIME = Utils.getStorage({
			storageName: 'LOGIN_CURRENT_TIME',
			storageType: 'localStorage'
		})
		const TTL = data.ttl || $store.userInfo.ttl || DEFAULT_VALID_TIME
		Utils.loginCountdown(LOGIN_CURRENT_TIME, TTL)
		
		$store.setUserInfo({
			userType: data.userType,
			beginTime: Utils.getDate().getTime
		})
	}
}

// 判断是否有效期内，参数为true时，返回时间秒数，false返回boolean值
const isValidTime = (isReturnTimeValue = false): number | boolean => {
	const $store = useCommonStore()
	const date = new Date(), currentTime = date.getTime()
	const loginCountdownTime = Math.ceil($store.userInfo.ttl! - (currentTime - $store.userInfo.beginTime) / 1000)
	return isReturnTimeValue ? loginCountdownTime : (loginCountdownTime && loginCountdownTime > 0)
}
// 判断token是否有效
const isValidToken = () => {
	const $store = useCommonStore()
	const token = $store.token
	const validTime = isValidTime()
	return token && validTime
}

router.beforeEach((to, from, next) => {
	const $store = useCommonStore()

	// 启动页面加载进度条
	NProgress.start()

	// 鉴权
	const isValidUserType = USER_TYPE_FN({
		userType: 'isAdministrator'
	})
	if(to.meta.isAuth && !isValidUserType) {// 鉴权失败
		if(!isValidToken()) return next({path: PATH_LOGIN})
		ElMessage.error('当前用户没有权限')
		return next(false)
	}

	// $store.userStatus = true 代表首次登录，需要去修改密码
	// if($store.userStatus && to.name === SET_PASSWORD) return next()
	if($store.userStatus) {
		if(to.name === SET_PASSWORD) return next()
		else return next({path: SET_PASSWORD})
	}

	if(isValidToken()) {
		// 已登录，禁止进入登录页和初始密码修改页
		if(to.name === LOGIN || to.name === SET_PASSWORD) return next({path: from.path})
		if(typeof isValidTime(true) === 'number') {
			
		}
		const isValidTimeResult = isValidTime(true)
		if(typeof isValidTimeResult === 'number' && isValidTimeResult <= RE_SIGN_IN_TIME) {
			reSignInFn()
			return next()
		}

		// 登录有效期内，两次操作间隔大于5分钟时，刷新 token 并更新倒计时
		const LOGIN_CURRENT_TIME = Utils.getStorage({
			storageName: 'LOGIN_CURRENT_TIME',
			storageType: 'localStorage'
		}) || Utils.getDate().getTime

		const TTL =  Utils.getStorage({
			storageName: 'LOGIN_COUNTDOWN',
			storageType: 'localStorage'
		}) || $store.userInfo.ttl || DEFAULT_VALID_TIME

		Utils.loginCountdown(LOGIN_CURRENT_TIME, TTL)
	} else {
		if(to.name === LOGIN) return next()
		// $store.userStatus && $store.setUserStatus(false)
		if(to.fullPath && to.fullPath !== PATH_LOGIN) {
			return next({
				path: PATH_LOGIN,
				query: {
					redirect: to.fullPath
				}
			})
		}
		return next({path: PATH_LOGIN})
	}
	next()
})

router.afterEach(to => {
	const $store = useCommonStore()
	if(!!to.meta.title && typeof to.meta.title === 'string') {
		document.title = `${$store.systemInfo.systemNameCN 
			? $store.systemInfo.systemNameCN + '-' + to.meta.title 
			: to.meta.title}`
	}

	// 进入首页时，初始化导航位置
	if(to.path === '/') $store.setPosiList([])

	// 结束页面加载进度条
	NProgress.done()
})

export default router
